package cn.com.libertymutual.saleplat.config;

import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.mobile.device.DeviceResolverHandlerInterceptor;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import cn.com.libertymutual.core.http.CloseableHttpClientSSL;
import cn.com.libertymutual.sp.biz.IdentifierMarkBiz;

/**
 * 启动 配置
 * @author bob.kuang
 * @version $Id: BootstrapConfig.java, v 0.1 2016年8月2日 上午12:11:47 bob.kuang Exp $
 */

@Configuration
@Order(1)
public class BootstrapConfig implements WebMvcConfigurer {
	@Autowired
	private RestTemplateProperties restTemplateProperties;

	@Resource
	private IdentifierMarkBiz identifierMarkBiz;
	

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 多个拦截器组成一个拦截器链

		registry.addInterceptor(deviceResolverHandlerInterceptor());

		// addPathPatterns 用于添加拦截规则
		// excludePathPatterns 用户排除拦截
		registry.addInterceptor(new AdminLocaleInterceptor(identifierMarkBiz)).addPathPatterns("/**").excludePathPatterns("/**.css", "/**.js",
				"/**.jpg", "/**.gif", "/**.png", "/**.pdf", "/**.html");
		// registry.addInterceptor(new
		// AdminLocaleInterceptor()).addPathPatterns("/**").excludePathPatterns(
		// excludeUri.split("\\,") );

		///super.addInterceptors(registry);
	}

	//@Bean
	public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() {
		return new DeviceResolverHandlerInterceptor();
	}

/*
	private Connector createSslConnector() {
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
		try {
			File truststore = new File("/Users/liaokailin/software/ca1/keystore");
			connector.setScheme("https");
			protocol.setSSLEnabled(true);
			connector.setSecure(true);
			connector.setPort(18443);
			protocol.setKeystoreFile(truststore.getAbsolutePath());
			protocol.setKeystorePass("123456");
			protocol.setKeyAlias("springboot");
			return connector;
		} catch (Exception ex) {
			throw new IllegalStateException("cant access keystore: [" + "keystore" + "]  ", ex);
		}
	}*/

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/soastatic/**").addResourceLocations("classpath:/public/").resourceChain(true);
	}

	/**
	 * 
	 * @return
	 */
	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();

		resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);

		resolver.setPrefix("/");
		resolver.setSuffix(".vm");
		return resolver;
	}

	@Bean("restTemplate")
	public RestTemplate restTemplate() {

		PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager();
		pollingConnectionManager.setMaxTotal(restTemplateProperties.getPollingConnection().getMaxTotal());
		pollingConnectionManager.setDefaultMaxPerRoute(restTemplateProperties.getPollingConnection().getDefaultMaxPerRoute());

		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		httpClientBuilder.setConnectionManager(pollingConnectionManager);

		HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());

		clientHttpRequestFactory.setConnectTimeout(restTemplateProperties.getConnectTimeout());
		clientHttpRequestFactory.setReadTimeout(restTemplateProperties.getReadTimeout());

		clientHttpRequestFactory.setBufferRequestBody(restTemplateProperties.isBufferRequestBody());

		RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

		List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
		HttpMessageConverter<?> converterTarget = null;
		for (HttpMessageConverter<?> item : converterList) {
			if (item.getClass() == StringHttpMessageConverter.class) {
				converterTarget = item;
				break;
			}
		}

		if (converterTarget != null) {
			converterList.remove(converterTarget);
		}
		HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
		converterList.add(converter);

		return restTemplate;

	}

	@Bean("restTemplateHttps")
	public RestTemplate restTemplateHttps() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

		HttpComponentsClientHttpRequestFactory clientHttpRequestFactory;
		try {
			clientHttpRequestFactory = CloseableHttpClientSSL.acceptsUntrustedCertsHttpClient(
					restTemplateProperties.getPollingConnection().getMaxTotal(),
					restTemplateProperties.getPollingConnection().getDefaultMaxPerRoute());

			clientHttpRequestFactory.setConnectTimeout(restTemplateProperties.getConnectTimeout());
			clientHttpRequestFactory.setReadTimeout(restTemplateProperties.getReadTimeout());

			clientHttpRequestFactory.setBufferRequestBody(restTemplateProperties.isBufferRequestBody());

			RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

			/*
			 * List<HttpMessageConverter<?>> converterList =
			 * restTemplate.getMessageConverters(); HttpMessageConverter<?> converterTarget
			 * = null; for (HttpMessageConverter<?> item : converterList) { if
			 * (item.getClass() == StringHttpMessageConverter.class) { converterTarget =
			 * item; break; } }
			 * 
			 * if (converterTarget != null) { converterList.remove(converterTarget); }
			 * HttpMessageConverter<?> converter = new
			 * StringHttpMessageConverter(StandardCharsets.UTF_8);
			 * converterList.add(converter);
			 */

			return restTemplate;

		} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("HTTPS创建失败");
			System.exit(-10);
		}

		return null;
	}

}
